package com.ruyuan.rapid.core.context;

import javax.management.Attribute;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public abstract class AttributeKey<T> {

    private static final Map<String, AttributeKey<?>> namedMap = new HashMap<>();

    public static final AttributeKey<Set<String>> MATCH_ADDRESS = create(Set.class);


    static {
        namedMap.put("MATCH_ADDRESS",MATCH_ADDRESS);
    }


    /**
     * 将对象转换成对应的对象
     * @param value
     * @return
     */
    public abstract T cast(Object value);

    public static AttributeKey<?> valueOf(String name) {
        return namedMap.get(name);
    }


    public static <T> AttributeKey<T> create(final Class<? extends T> valueClass){
        return new SimpleAttributeKey(valueClass);
    }

    public static class SimpleAttributeKey<T> extends AttributeKey<T>{

        private final Class<T> valueClass;

        SimpleAttributeKey(final Class<T> clazz){
            this.valueClass = clazz;
        }

        @Override
        public T cast(Object value) {
            return valueClass.cast(value);
        }

        @Override
        public String toString() {
            if(valueClass != null){
                StringBuilder sb = new StringBuilder(getClass().getName());
                sb.append("<");
                sb.append(valueClass.getName());
                sb.append(">");
                return sb.toString();
            }else {
                return super.toString();
            }
        }
    }
}
